package com.learning.jquizenglish.common.service;

import com.learning.jquizenglish.common.controller.AudioStreamingController;

import android.app.Service;
import android.content.Intent;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnBufferingUpdateListener;
import android.media.MediaPlayer.OnErrorListener;
import android.media.MediaPlayer.OnPreparedListener;
import android.os.IBinder;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class MediaPlayerService extends Service implements OnBufferingUpdateListener, OnErrorListener, OnPreparedListener{

	private static final String ACTION_PLAY = "PLAY";
    private static String mUrl;
    private static MediaPlayerService mInstance = null;
    private static MediaCallBack mListener;
    
    private MediaPlayer mMediaPlayer = null;    // The Media Player
    private int mBufferPosition;
    private Button btnPlayPause;
    
    // indicates the state our service:
    enum State {
        Retrieving, // the MediaRetriever is retrieving music
        Stopped, // media player is stopped and not prepared to play
        Preparing, // media player is preparing...
        Playing, // playback active (media player ready!). (but the media player may actually be
                    // paused in this state if we don't have audio focus. But we stay in this state
                    // so that we know we have to resume playback once we get focus back)
        Paused,
        Ready
        // playback paused (media player ready!)
    };

    State mState = State.Retrieving;

    @Override
    public void onCreate() {
        mInstance = this;
    }
    
	@Override
	public IBinder onBind(Intent arg0) {
		return null;
	}
	
	@Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        if (intent.getAction().equals(ACTION_PLAY)) {
            mMediaPlayer = new MediaPlayer(); // initialize it here
            mMediaPlayer.setOnPreparedListener(this);
            mMediaPlayer.setOnErrorListener(this);
            mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
            initMediaPlayer();
        }
        return START_STICKY;
    }

	private void initMediaPlayer() {
        try {
        	if (mListener!=null) {
				btnPlayPause = mListener.getPlayPauseButton();
			}
            mMediaPlayer.setDataSource(mUrl);
//          mMediaPlayer.prepareAsync(); // prepare async to not block main thread
            mMediaPlayer.prepare();
            mMediaPlayer.setOnBufferingUpdateListener(this);
            if (btnPlayPause!=null) {
				btnPlayPause.setText("Load Audio...");
			}
        } catch (Exception e) {
            e.printStackTrace();
        } 
        mState = State.Preparing;
    }

	public void setButton(Button btn){
		btnPlayPause = btn;
		btnPlayPause.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				switch (mState) {
				case Ready:
					startAudio();
					break;
				case Paused:
					startAudio();
					break;
				case Playing:
					pauseAudio();
					break;
				default:
					break;
				}
			}
		});
	}
	
    public void restartMusic() {
        // Restart music
    }
    
	@Override
	public void onPrepared(MediaPlayer arg0) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public boolean onError(MediaPlayer arg0, int arg1, int arg2) {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public void onBufferingUpdate(MediaPlayer arg0, int percent) {
		if (percent == 100) {
			mState = State.Ready;
			mMediaPlayer.setOnBufferingUpdateListener(null);
			if (btnPlayPause!=null) {
				btnPlayPause.setText("Play");
			}
		}
	}
	
	@Override
    public void onDestroy() {
        if (mMediaPlayer != null) {
            mMediaPlayer.release();
        }
        mState = State.Retrieving;
    }
	
	public MediaPlayer getMediaPlayer() {
        return mMediaPlayer;
    }

    public void pauseAudio() {
        if (mState.equals(State.Playing)) {
            mMediaPlayer.pause();
            mState = State.Paused;
        }
    }

    public void startAudio() {
        if (!mState.equals(State.Preparing) &&!mState.equals(State.Retrieving)) {
            mMediaPlayer.start();
            mState = State.Playing;
        }
    }

    public boolean isPlaying() {
        if (mState.equals(State.Playing)) {
            return true;
        }
        return false;
    }

    public int getMusicDuration() {
        // Return current music duration
    	return -1;
    }

    public int getCurrentPosition() {
        // Return current position
    	return -1;
    }

    public int getBufferPercentage() {
        return mBufferPosition;
    }

    public void seekMusicTo(int pos) {
        // Seek music to pos
    }

    public static void setCallBack(MediaCallBack listener){
    	mListener = listener;
    }
    
    public static MediaPlayerService getInstance() {
        return mInstance;
    }

    public static void setStreamingUrl(String url) {
        mUrl = url;
    }
    
    public interface MediaCallBack{
    	public Button getPlayPauseButton();
    }

}
